//
//  CommunityDetailViewController.m
//  CarLife
//
//  Created by yu on 2019/4/1.
//  Copyright © 2019年 jpas. All rights reserved.
//

#import "CommunityDetailViewController.h"
#import "KTTagListView.h"
#import "CommunityModel.h"
#import "CDCell.h"
#import "CommentCell.h"
#import "CommentModel.h"
#import "AllCommentViewController.h"
#import "CommentHandleView.h"
#import "PPStickerInputView.h"
#import "PPUtil.h"
#import "UserProfileViewController.h"

static NSString *Identifier = @"CommunityDetailIdentitifier";
static NSString *kCDCellIdentifier = @"CDCellIdentitifier";
static NSString *kCCCellIdentifier = @"CCCellIdentitifier";

@interface CommunityDetailViewController ()<UITableViewDelegate,UITableViewDataSource,KTTagListViewDataSource, KTTagListViewDelegate,CommentDelegate,HandleDelegate,PPStickerInputViewDelegate>

@property (nonatomic, strong) KTTagListView *tagList;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (weak, nonatomic) IBOutlet CommentHandleView *HandleView;
@property (nonatomic, strong) PPStickerInputView *inputView;

@end

@implementation CommunityDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    self.navigationItem.title = @"动态详情";
    [self.tableView registerNib:NIB_NAMED(@"CDCell") forCellReuseIdentifier:kCDCellIdentifier];
    [self.tableView registerNib:NIB_NAMED(@"CommentCell") forCellReuseIdentifier:kCCCellIdentifier];
    
    [self.dataSource addObjectsFromArray:[self creatModelsWithCount:10]];
    [self.HandleView setDelegate:self];
    [self.view addSubview:self.inputView];
}

- (PPStickerInputView *)inputView
{
    if (!_inputView) {
        _inputView = [[PPStickerInputView alloc] init];
        _inputView.delegate = self;
    }
    return _inputView;
}

#pragma mark - PPStickerInputViewDelegate

- (void)stickerInputViewDidClickSendButton:(PPStickerInputView *)inputView
{
    NSString *plainText = inputView.plainText;
    if (!plainText.length) {
        return;
    }
    PPLog(@"plainText = %@",plainText);
//    NSMutableArray *messages = [[NSMutableArray alloc] initWithArray:self.messages];
//    [messages addObject:plainText];
//    self.messages = messages;
//    [inputView clearText];
//
//    [self.tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    CGFloat height = [self.inputView heightThatFits];
    CGFloat minY = CGRectGetHeight(self.view.bounds) - height - PP_SAFEAREAINSETS(self.view).bottom;
    self.inputView.frame = CGRectMake(0, kScreenHeight, CGRectGetWidth(self.view.bounds), height);
    //    self.inputView.backgroundColor = [UIColor orangeColor];
    
//    self.tableView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetMinY(self.inputView.frame));
}

#pragma mark -
- (void)commentAction:(UIButton *)button
{
    [self.inputView.textView becomeFirstResponder];
}

#pragma mark - CommentDelegate -

- (void)showAllComments:(NSInteger)index
{
    CommentModel *cModel = self.dataSource[index];
//    PPLog(@"一级回复内容 = %@",cModel.content);
    PPLog(@"二级回复条数 = %ld",cModel.secondCommentsArray.count);
    
    for (SecondCommentModel *scModel in cModel.secondCommentsArray) {
        PPLog(@"二级回复内容 = %@",scModel.content);

        if (scModel.thirdCommentArray.count != 0) {
            PPLog(@"【三级回复数量 = %ld】",scModel.thirdCommentArray.count);
            for (ThirdCommentModel *tcModel in scModel.thirdCommentArray) {
                PPLog(@"***三级回复 = %@",tcModel.content);
            }
        }

    }
    
    
    
    AllCommentViewController *ac = [AllCommentViewController new];
    ac.cModel = cModel;
    [self.navigationController pushViewController:ac animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return !section ? 1 : self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        return [self.tableView cellHeightForIndexPath:indexPath model:self.cModel keyPath:@"cModel" cellClass:[CDCell class] contentViewWidth:[self cellContentViewWith]];
    } else {
        CommentModel *cModel = self.dataSource[indexPath.row];
        return [self.tableView cellHeightForIndexPath:indexPath model:cModel keyPath:@"cModel" cellClass:[CommentCell class] contentViewWidth:[self cellContentViewWith]];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        CDCell *cell = [tableView dequeueReusableCellWithIdentifier:kCDCellIdentifier];
        cell.cModel = self.cModel;
        @weakify(self);
        [cell setIconTapBlock:^{
            @strongify(self);
            [self.navigationController pushViewController:[UserProfileViewController new] animated:YES];
        }];
        return cell;
    } else {
        CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kCCCellIdentifier];
        cell.delegate = self;
        cell.allCommentBtn.tag = indexPath.row;
        CommentModel *cModel = self.dataSource[indexPath.row];
        cell.cModel = cModel;
        return cell;
    }
}


- (NSArray *)creatModelsWithCount:(NSInteger)count
{
    NSArray *commentArray = @[@"灯火辉煌的街头，突然袭来了一阵寒流，遥远的温柔，解不了的近愁，是否在随波逐流，夜深人静的时候，我就潜伏在你的伤口，梦是氢气球，向天外飞走，最后都化作乌有一个人在梦游，像奔跑的犀牛，不到最后不罢休",
                              @"夜深人静的时候，我就潜伏在你的伤口，梦是氢气球，向天外飞走，最后都化作乌有",
                              @"一个人在梦游，像奔跑的犀牛",
                              @"爱若需要厮守，恨更需要自由，爱与恨纠缠不休，我拿什么拯救，当爱覆水难收，谁能把谁保佑，心愿为谁等待",
                              @"我拿什么拯救，情能见血封喉，谁能把谁保佑，能让爱永不朽",
                              @"夜深人静的时候，我就潜伏在你的伤口",
                              @"梦是氢气球",
                              @"灯火辉煌的街头。",
                              @"遥远的温柔，解不了的近愁",
                              @"不到最后不罢休......",
                              ];
    
    NSMutableArray *resArr = [NSMutableArray new];
    
    for (int i = 0; i < count; i++) {
        // 一级回复
        int commentRandomIndex = arc4random_uniform(10);
        CommentModel *model = [CommentModel new];
        model.content = commentArray[commentRandomIndex];
        
        // 二级回复
        int random = arc4random_uniform(10);
        NSMutableArray *temp = [NSMutableArray new];
        for (int i = 0; i < random; i++) {
            int randomIndex = arc4random_uniform(10);
            SecondCommentModel *scModel = [SecondCommentModel new];
            scModel.content = commentArray[randomIndex];
            [temp addObject:scModel];
            
            // 三级回复
            int random1 = arc4random_uniform(2);
            NSMutableArray *temp1 = [NSMutableArray new];
            for (int i = 0; i < random1; i++) {
                int randomIndex1 = arc4random_uniform(2);
                ThirdCommentModel *tcModel = [ThirdCommentModel new];
                tcModel.content = commentArray[randomIndex1];
                [temp1 addObject:tcModel];
            }
            if (temp1.count) {
                scModel.thirdCommentArray = [temp1 copy];
            }
        }
        if (temp.count) {
            model.secondCommentsArray = [temp copy];
        }
        
        [resArr addObject:model];
    }
    return [resArr copy];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = kBackgroundColor;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 5, kScreenWidth, 45)];
    view.backgroundColor = [UIColor whiteColor];
    
    self.tagList = [[KTTagListView alloc] initWithFrame:CGRectMake(17, 7.5, 200, 30)];
//    self.tagList.backgroundColor = [UIColor lightGrayColor];
    self.tagList.dataSource = self;
    self.tagList.delegate = self;
    [view addSubview:self.tagList];
    [bgView addSubview:view];
//    self.tagList.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    return !section ? nil : bgView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return !section ? 0.001 : 50.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001f;
}

#pragma mark - KTTagListViewDataSourceAndDelegate
- (NSInteger)numberOfItemsInTagListView:(KTTagListView *)tagListView {
    return 2;
}

- (UIButton *)tagListView:(KTTagListView *)tagListView cellAtIndex:(NSInteger)index {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@[@"评论 7",@"点赞 10"][index] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    button.titleLabel.font = [UIFont systemFontOfSize:15];
    return button;
}

- (void)tagListView:(KTTagListView *)tagListView willDisplayCell:(UIButton *)button AtIndex:(NSInteger)index {
    if (index == 0) {
        [button setTitleColor:kTextBlackColor forState:UIControlStateNormal];
        button.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Semibold", 16.5);
    } else {
        [button setTitleColor:kTextGrayColor forState:UIControlStateNormal];
        button.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Regular", 16.5);
    }
}

- (CGFloat)minimumWidthSpacingForCellInTagListView:(KTTagListView *)tagListView {
    return 20;
}

- (void)tagListView:(KTTagListView *)tagListView didSelectAtIndex:(NSInteger)index {
    UIScrollView *scroll = tagListView.subviews.firstObject;
    for (UIView *button in scroll.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            if (((UIButton *)button).tag == index) {
                [(UIButton *)button setTitleColor:kTextBlackColor forState:UIControlStateNormal];
                ((UIButton *)button).titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Semibold", 16.5);
            } else {
                [(UIButton *)button setTitleColor:kTextGrayColor forState:UIControlStateNormal];
                ((UIButton *)button).titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Regular", 16.5);
            }
        }
    }
}

- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7横屏
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

//
//- (KTTagListView *)tagList {
//    if (_tagList == nil) {
//        _tagList = [[KTTagListView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
//        _tagList.frame = CGRectMake(0, 0, kScreenWidth, 40);
//        _tagList.backgroundColor = [UIColor lightGrayColor];
//        _tagList.dataSource = self;
//        _tagList.delegate = self;
//    }
//    return _tagList;
//}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setWhiteNavigationBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setDefaultNavigationBar];
}

@end
